#include "persontaskgantt.h"

class PersonTaskModel : public QAbstractTableModel
{
public:
    QList<PersonTask> m_tasks;
    QList<QString> m_horHeaderData;
    QDate m_startDate;
    QDate m_endDate;
    int m_modelFlag =0;
public:
    PersonTaskModel(QObject *parent = 0)
        : QAbstractTableModel(parent)
    {
    }

    /*reimp*/ int rowCount(const QModelIndex &index = QModelIndex()) const override
    {
        return index.isValid() ? 0 : m_tasks.size();
    }
    /*reimp*/ int columnCount(const QModelIndex &index = QModelIndex()) const override
    {
        return index.isValid() ? 0 : 6;
    }
    /*reimp*/ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override
    {
        QDate s1,s2;
        QString s3;
    //    qDebug()<<"m_modelFlag:"<<m_modelFlag<<"title:"<<m_tasks[index.row()].title;
        if (index.isValid() && index.row() < rowCount() && index.column() < columnCount()) {
            switch (index.column()) {
            case 0:
                return (role == Qt::DisplayRole)
                           ? QVariant::fromValue(m_tasks[index.row()].title)
                           : QVariant();
            case 1:
                return (role == Qt::DisplayRole)
                           ? QVariant::fromValue(( int )KDGantt::TypeTask)
                           : QVariant();
            case 2:
                if(m_tasks[index.row()].start<=m_startDate)
                    s1=m_startDate;
                else
                    s1=m_tasks[index.row()].start;
                return (role == KDGantt::StartTimeRole || role == Qt::DisplayRole)
                           ? QVariant::fromValue(s1)
                           : QVariant();
            case 3:
                if(m_tasks[index.row()].end>=m_endDate)
                    s2=m_endDate;
                else
                    s2=m_tasks[index.row()].end;
                return (role == KDGantt::EndTimeRole || role == Qt::DisplayRole)
                           ? QVariant::fromValue(s2)
                           : QVariant();
            case 4:
                if(m_modelFlag==1)
                    s3= m_tasks[index.row()].developName;
                else if(m_modelFlag==2)
                    s3= m_tasks[index.row()].projectName;
                else
                    s3="-";
                return (role == Qt::DisplayRole)
                           ? QVariant::fromValue(s3)
                           : QVariant();
            case 5:
                return (role == Qt::DisplayRole)
                           ? QVariant::fromValue(m_tasks[index.row()].consumed)
                           : QVariant();
            }
        }

        return QVariant();
    }

    void setModelData(const QList<PersonTask> &datas)
    {
        // qDebug()<<"setModelData:"<<QDateTime::currentDateTime();
        //重置model数据之前调用beginResetModel，此时会触发modelAboutToBeReset信号
        beginResetModel();
        //重置model中的数据
        m_tasks=datas;
        //数据设置结束后调用endResetModel，此时会触发modelReset信号
        endResetModel();
        //注意：reset model后，选中的item会失效，我们可以自己写保存和恢复选中项的逻辑
        //如果表的行列数是固定的，只是数据变更了，我们可以用 dataChanged 信号来请求刷新。
        //emit dataChanged(index(0,0),index(RowMax-1,ColMax-1),QVector<int>());
    }
    bool setHorHeaderData(const QList<QString> &headers)
    {
        // qDebug()<<"setHorHeaderData:"<<QDateTime::currentDateTime();
        m_horHeaderData=headers;
        emit headerDataChanged(Qt::Horizontal, 0, headers.count()-1);
        return true;
    }

    QVariant headerData(int section, Qt::Orientation orientation, int role) const override
    {
        //qDebug()<<"headerData:"<<section<<QDateTime::currentDateTime();
        if(orientation == Qt::Horizontal){
            //这里我们只设置居中对齐和文本
            if (role == Qt::DisplayRole){
                //这里把横项列表头的文本设计为可以设置的
                if(section>=0 && section<m_horHeaderData.count())
                    return m_horHeaderData.at(section);
                return QString("Col %1").arg(section + 1);
            }else if(role == Qt::TextAlignmentRole){
                return Qt::AlignCenter;
            }
        }else{
            if (role == Qt::DisplayRole){
                qDebug()<<"headerdata:"<<section;
                return QString("Row %1").arg(section + 1);
            }
            else if(role == Qt::TextAlignmentRole)
                return Qt::AlignCenter;
        }
        return QVariant();
    }

    bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role) override
    {
        qDebug()<<"setHeaderData:"<<QDateTime::currentDateTime();
        if (value != headerData(section, orientation, role)) {
            m_horHeaderData[section] = value.toString();
            emit headerDataChanged(orientation, section, section);
            return true;
        }
        return false;
    }

    void moveRow(int from, int to)
    {
        if (from == to)
            return;
        if (from >= m_tasks.size() || to >= m_tasks.size() + 1)
            return;

        if (beginMoveRows(QModelIndex(), from, from, QModelIndex(), to)) {
            m_tasks.move(from, to);
            endMoveRows();
        } else {
            assert(0);
        }
    }
};

class MyDateTimeScaleFormatter : public KDGantt::DateTimeScaleFormatter
{
public:
    MyDateTimeScaleFormatter() : DateTimeScaleFormatter(Month, "MM"){}

//    /*reimp*/QDateTime nextRangeBegin(const QDateTime& datetime) const
//    {
//        return currentRangeBegin(datetime).addMonths(1);
//    }
//    /*reimp*/QDateTime currentRangeBegin(const QDateTime& datetime) const
//    {
//        return datetime;
//    }

    /*reimp*/QString text(const QDateTime& dt) const
    {
        return QObject::tr("%1年%2月").arg(dt.date().year()).arg(dt.date().month());
    }
};

PersonTaskGantt::PersonTaskGantt(QWidget *parent)
    : QWidget{parent}
{
    m_view = new KDGantt::View();
    //设置甘特图和列表view的显示比例
    m_view->splitter()->setStretchFactor(0, 1);
    m_view->splitter()->setStretchFactor(1, 4);

    //设置甘特图的表头
    m_dataGrid = new KDGantt::DateTimeGrid();
    KDGantt::DateTimeScaleFormatter *upperFormatter,*lowerFormatter;

    m_dataGrid->setUserDefinedUpperScale(new MyDateTimeScaleFormatter());

    lowerFormatter = new KDGantt::DateTimeScaleFormatter(KDGantt::DateTimeScaleFormatter::Day,
                                                         QString::fromLatin1("dd"),
                                                         QString::fromLatin1("%1"),
                                                         Qt::AlignHCenter);
    m_dataGrid->setUserDefinedLowerScale(lowerFormatter);
    m_dataGrid->setScale(KDGantt::DateTimeGrid::ScaleUserDefined);
    m_dataGrid->setDayWidth(38.);//设置甘特图的每天的宽度
    m_view->setGrid(m_dataGrid);
    m_view->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    m_model = new PersonTaskModel();

    QDate curDateDate =QDate::currentDate();
    m_model->m_startDate=curDateDate.addDays(-21);
    m_model->m_endDate=curDateDate.addDays(9);

    //设置列表view的表头
    m_model->m_horHeaderData.append("任务名称");
    m_model->m_horHeaderData.append("类型");
    m_model->m_horHeaderData.append("开始日期");
    m_model->m_horHeaderData.append("结束日期");
    m_model->m_horHeaderData.append("研发人员");
    m_model->m_horHeaderData.append("累计耗时");

    m_pageBar = new QPageBar();

    m_layoutGantt = new QVBoxLayout();
    m_layoutGantt->addWidget(m_view,9);
    m_layoutGantt->addWidget(m_pageBar,1);
    setLayout(m_layoutGantt);

    m_view->setModel(m_model);

    auto *tw = qobject_cast<QTreeView *>(m_view->leftView());
    tw->header()->setStyleSheet("QHeaderView::section{background-color: #1E90FF;color: white;font-size:50;font-weight:bold;}");
    tw->setColumnWidth(0,380);
    tw->setColumnWidth(1,40);
    tw->setColumnWidth(2,80);
    tw->setColumnWidth(3,80);
    tw->setColumnWidth(4,60);
    tw->setColumnWidth(5,50);
    tw->setAlternatingRowColors(true);
    tw->setStyleSheet("QTreeView::item{height:30px;alternate-background-color:rgb(135,206,235);}");
    tw->setColumnHidden(1,true);
}

void PersonTaskGantt::SetGanttModel()
{
    qDebug()<<"model row size:"<<m_model->rowCount()<<"col size:"<<m_model->columnCount();
    m_view->setModel(m_model);

}

void PersonTaskGantt::SetModelFlag(int modelflag)
{
    m_model->m_modelFlag=modelflag;
}

void PersonTaskGantt::BindModelData(const QList<PersonTask> &modeldata)
{
    m_model->setModelData(modeldata);
}

void PersonTaskGantt::SetStartEndData(QDate &startdate, QDate &enddate)
{
    m_model->m_startDate = startdate;
    m_model->m_endDate = enddate;
    qDebug()<<"startdate:"<<m_model->m_startDate<<"enddate:"<<m_model->m_endDate;
}
